package com.hx.delegate.strategy.mvc;

import com.hx.delegate.strategy.mvc.controllers.UserController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author： Huathy
 * @ClassPath： com.hx.delegate.mvc.DispatcherServlet
 * @Date： 2021-08-30 21:24
 * @Description： 委派模式 + 策略模式 + 简单工厂 + 单例模式
 */
public class DispatcherServlet extends HttpServlet {
    List<Handler> handlerMapping = new ArrayList<>();

    @Override
    public void init() throws ServletException {
        Class<?> clazz = UserController.class;
        try {
            handlerMapping.add(new Handler().setController(clazz.newInstance())
                    .setMethod(clazz.getMethod("getUserById", String.class))
            .setUrl("/web/getUserById.do"));
        } catch (InstantiationException | NoSuchMethodException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //完成调度
        try {
            doDispatch(req,resp);
        } catch (InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
        String uri = req.getRequestURI();
        Handler handler = null;
        for (Handler hdl : handlerMapping) {
            if(uri.equals(hdl.getUrl())){
                handler = hdl;
                break;
            }
        }
        Object obj = handler.getMethod().invoke(handler.getController(), req.getParameter("uid"));
        resp.getWriter().println(obj);
    }

    class Handler{
        private Object controller;
        private Method method;
        private String url;

        public Object getController() {
            return controller;
        }

        public Handler setController(Object controller) {
            this.controller = controller;return this;
        }
        public Method getMethod() {
            return method;
        }

        public Handler setMethod(Method method) {
            this.method = method;return this;
        }

        public String getUrl() {
            return url;
        }

        public Handler setUrl(String url) {
            this.url = url;return this;
        }
    }
}
